//
//  WQOAuthController.swift
//  sanwuWeibo
//
//  Created by 王先强 on 15/12/7.
//  Copyright © 2015年 王先强. All rights reserved.
//

import UIKit
import SVProgressHUD

class WQOAuthController: UIViewController {

    var webView: UIWebView?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        view.backgroundColor?.WQRandomColor
        oauthViewSetting()
        oauthLoading()

    }
    
    override func loadView() {
        webView = UIWebView()
        webView?.delegate = self
        view = webView
    }
    

}
// MARK: - OAuth认证加载
extension WQOAuthController {
    
    func oauthLoading() {
        webView!.loadRequest(WQNetTool.shareTool.oauthURLRequest)
    }
}
// MARK: - webView代理方法实现
extension WQOAuthController: UIWebViewDelegate {
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        
        guard let oauthUrl = request.URL where oauthUrl.host == "www.baidu.com" else {
            print(request.URL?.query)
            print(request.URL?.host)
            return true
        }
        
        guard let urlStr = oauthUrl.query where urlStr.hasPrefix("code=") else {
            print("取消授权")
            return false
        }
        
        let code = urlStr.substringFromIndex("code=".endIndex)
        
        //利用WQAccountViewModel的单例加载用户的accessToken和userInfo
        WQAccountViewModel.sharedAccount.loadAccessTokenAndUserInfo(code) { (success, failure) -> () in
            
            if failure != nil {
                print(failure)
                return
            }
           
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                // 成功获取到定义的access
                NSNotificationCenter.defaultCenter().postNotificationName(WQSwitchRootViewControllerNotification, object: "welcome")
            })
        }

        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}



// MARK: - OAuth认证界面设置
extension WQOAuthController {
    
    func oauthViewSetting() {
        view.backgroundColor = UIColor().WQRandomColor
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "closeOAuthView")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
        /// 自动填充用户名和密码 － web 注入（以代码的方式向web页面添加内容）

        title = "登陆新浪微博"
    }
    @objc private func autoFill() {
        
        let js = "document.getElementById('userId').value = '18580172452';" +
        "document.getElementById('passwd').value = '18580172452qqqq';"
        
        // 让 webView 执行 js
        webView!.stringByEvaluatingJavaScriptFromString(js)
    }
    
    func closeOAuthView() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}
